package com.example.springbootdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springbootdemo.constant.CommonConst;
import com.example.springbootdemo.service.IBaseService;
import com.example.springbootdemo.utils.PageUtils;
import org.aspectj.lang.annotation.Before;

/**
 * @author xuwangqi
 * @date 2021/5/24 10:53
 **/
public class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements IBaseService<T> {
    @Override
    public PageUtils<T> queryForPage(int page, int limit) {
        page = checkPage(page);
        limit = checkLimit(limit);
        IPage<T> iPage = this.page(new Page<>(page, limit));
        return new PageUtils<>(iPage);
    }

    @Override
    public PageUtils<T> queryForPage(int page, int limit, QueryWrapper<T> queryWrapper) {
        page = checkPage(page);
        limit = checkLimit(limit);
        IPage<T> iPage = this.page(new Page<>(page, limit), queryWrapper);
        return new PageUtils<>(iPage);
    }

    private int checkPage(int page) {
        page = page < 0 ? CommonConst.PAGE.DEFAULT_PAGE : page;
        return page;
    }

    private int checkLimit(int limit) {
        limit = limit < 0 ? CommonConst.PAGE.DEFAULT_LIMIT :
                limit <= CommonConst.PAGE.DEFAULT_MAX_LIMIT ? limit : CommonConst.PAGE.DEFAULT_MAX_LIMIT;
        return limit;
    }


}
